package com.lkd.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.google.common.base.Strings;
import com.google.common.collect.Lists;
import com.lkd.common.VMSystem;
import com.lkd.config.TopicConfig;
import com.lkd.contract.*;
import com.lkd.dao.TaskDao;
import com.lkd.emq.MqttProducer;
import com.lkd.entity.TaskDetailsEntity;
import com.lkd.entity.TaskEntity;
import com.lkd.entity.TaskStatusTypeEntity;
import com.lkd.entity.VendingMachineEntity;
import com.lkd.exception.LogicException;
import com.lkd.feign.UserServiceFeignClient;
import com.lkd.feign.VmServiceFeignClient;
import com.lkd.http.vo.*;
import com.lkd.vo.Pager;
import com.lkd.vo.UserVO;
import com.lkd.vo.UserWorkVO;
import com.lkd.service.TaskDetailsService;
import com.lkd.service.TaskService;
import com.lkd.service.TaskStatusTypeService;
import com.lkd.service.TaskTypeService;
import com.lkd.vo.VmVO;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.eclipse.paho.client.mqttv3.MqttException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ObjectUtils;
import rx.BackpressureOverflow;

import javax.security.auth.login.LoginException;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.Period;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

@Service
@Slf4j
public class TaskServiceImpl extends ServiceImpl<TaskDao, TaskEntity> implements TaskService {

    @Autowired
    private TaskStatusTypeService taskStatusTypeService;

    @Autowired
    private TaskTypeService taskTypeService;
    @Autowired
    private UserServiceFeignClient userServiceFeignClient;
    @Autowired
    private TaskDetailsService taskDetailsService;

    @Autowired
    private StringRedisTemplate redisTemplate;

    // 查询所有工单状态
    @Override
    public List<TaskStatusTypeEntity> getAllStatus() {
        return taskStatusTypeService.list();
    }

    /*
    * 搜素哦工单
    * */
    @Override
    public Pager<TaskEntity> search(Long pageIndex, Long pageSize, String innerCode, Integer userId, String taskCode, Integer status, Boolean isRepair, LocalDate start, LocalDate end) {
        //1.分页+条件查询工单
        //1-1 分页
        Page<TaskEntity> page = new Page<>(pageIndex, pageSize);
        // 1-2 条件
        LambdaQueryWrapper<TaskEntity> qw = new LambdaQueryWrapper<>();
        // 设备编号
        qw.eq(StrUtil.isNotEmpty(innerCode),TaskEntity::getInnerCode,innerCode);
        //干活人id
        qw.eq(ObjectUtil.isNotEmpty(userId),TaskEntity::getUserId,userId);
        //工单编号
        qw.eq(StrUtil.isNotEmpty(taskCode),TaskEntity::getTaskCode,taskCode);
        //工单状态
        qw.eq(ObjectUtil.isNotEmpty(status),TaskEntity::getTaskStatus,status);
        //是否为运维工单
        if(ObjectUtil.isNotEmpty(isRepair) && isRepair == true){
            //是运维
            qw.in(TaskEntity::getProductTypeId,List.of(1,3,4));
        }else if(ObjectUtil.isNotEmpty(isRepair) && isRepair==false){
            //是运营
            qw.eq(TaskEntity::getProductTypeId,2);
        }
        //日期范围查询
        if(ObjectUtil.isNotEmpty(start) && ObjectUtil.isNotEmpty(end)){
            //转化日期时间对象
            LocalDateTime minTime = start.atTime(LocalTime.MIN);//2020-01-01 00:00:01
            LocalDateTime maxTime = end.atTime(LocalTime.MAX);// 2020-12-31 23：59：59
            qw.between(TaskEntity::getCreateTime,minTime,maxTime);
        }
        //1-3 排序
        qw.orderByDesc(TaskEntity::getUpdateTime);
        //1-4查询
        this.page(page,qw);
        //2.返回结果
        return Pager.build(page);
    }


    // 获取人员排名
    @Override
    public List<UserWorkVO> getUserWorkTop10(LocalDate startTime, LocalDate endTime, Boolean isRepair, Long regionId) {
        // select
        //     user_name,
        //     count(*) user_id
        // from
        //     tb_task
        // where
        //     task_status = 4
        //     and
        //     update_time >= '2022-12-01 00:00:00'
        //     and
        //     update_time < '2023-01-01 00:00:00'
        //     and
        //     region_id = ?
        //     and
        //     product_type_id = ?
        // group by user_name
        // order by num desc
        // limit 10

        QueryWrapper<TaskEntity> queryWrapper = new QueryWrapper<TaskEntity>();
        queryWrapper.select(" user_name,count(*) user_id ");
        queryWrapper.last("order by user_id desc  limit 10");
        queryWrapper.lambda()
                .eq(TaskEntity::getTaskStatus, VMSystem.TASK_STATUS_FINISH)
                .ge(TaskEntity::getUpdateTime, startTime)
                .lt(TaskEntity::getUpdateTime, endTime.plusDays(1))
                .groupBy(TaskEntity::getUserName);

        if (regionId > 0) {
            queryWrapper.lambda().eq(TaskEntity::getRegionId, regionId);
        }
        if (isRepair) {
            queryWrapper.lambda().ne(TaskEntity::getProductTypeId, VMSystem.TASK_TYPE_SUPPLY);
        } else {
            queryWrapper.lambda().eq(TaskEntity::getProductTypeId, VMSystem.TASK_TYPE_SUPPLY);
        }

        List<TaskEntity> resultList = this.list(queryWrapper);

        // 将 List<TaskEntity> 变为 List<UserWorkVO>
        List<UserWorkVO> userWorks = resultList.stream().map(taskEntity -> {
            var userWorkVO = new UserWorkVO();
            userWorkVO.setUserName(taskEntity.getUserName());
            userWorkVO.setWorkCount(taskEntity.getUserId());
            return userWorkVO;
        }).collect(Collectors.toList());

        return userWorks;
    }

    /**
     * 获取工单报表
     *
     * @param start
     * @param end
     * @return
     */
    @Override
    public List<TaskCollectVO> getTaskReport(LocalDate start, LocalDate end) {
        List<TaskCollectVO> taskCollectVOList = Lists.newArrayList();
        //从开始日期到截至日期，逐条统计
        start.datesUntil(end.plusDays(1), Period.ofDays(1))
                .forEach(date -> {
                    var taskCollectVO = new TaskCollectVO();
                    taskCollectVO.setCollectDate(date);
                    taskCollectVO.setProgressCount(count(date, VMSystem.TASK_STATUS_PROGRESS)); //进行中工单数
                    taskCollectVO.setFinishCount(count(date, VMSystem.TASK_STATUS_FINISH));//完成工单数
                    taskCollectVO.setCancelCount(count(date, VMSystem.TASK_STATUS_CANCEL));//取消工单数
                    taskCollectVOList.add(taskCollectVO);
                });
        return taskCollectVOList;
    }

    /**
     * 获取用户工作量详情
     *
     * @param userId
     * @param start
     * @param end
     * @return
     */
    @Override
    public UserWorkVO getUserWork(Integer userId, LocalDateTime start, LocalDateTime end) {
        var userWork = new UserWorkVO();
        userWork.setUserId(userId);

        //获取用户完成工单数
        var workCount = this.getCountByUserId(userId, VMSystem.TASK_STATUS_FINISH, start.toLocalDate(), end);
        userWork.setWorkCount(workCount);

        //获取工单总数
        var total = this.getCountByUserId(userId, null, start.toLocalDate(), end);
        userWork.setTotal(total);

        //获取用户拒绝工单数
        var cancelCount = this.getCountByUserId(userId, VMSystem.TASK_STATUS_CANCEL, start.toLocalDate(), end);
        userWork.setCancelCount(cancelCount);

        //获取进行中得工单数
        var progressTotal = this.getCountByUserId(userId, VMSystem.TASK_STATUS_PROGRESS, start.toLocalDate(), end);
        userWork.setProgressTotal(progressTotal);

        return userWork;
    }

    //根据工单状态，获取用户指定时间段范围的工单数
    private Integer getCountByUserId(Integer userId, Integer taskStatus, LocalDate start, LocalDateTime end) {
        var qw = new LambdaQueryWrapper<TaskEntity>();
        qw
                .ge(TaskEntity::getUpdateTime, start)
                .le(TaskEntity::getUpdateTime, end);
        if (taskStatus != null) {
            qw.eq(TaskEntity::getTaskStatus, taskStatus);
        }
        if (userId != null) {
            qw.eq(TaskEntity::getUserId, userId);
        }
        return this.count(qw);
    }

    /**
     * 按时间和状态进行统计
     *
     * @param start
     * @param taskStatus
     * @return
     */
    private int count(LocalDate start, Integer taskStatus) {
        var qw = new LambdaQueryWrapper<TaskEntity>();
        qw
                .ge(TaskEntity::getUpdateTime, start)
                .lt(TaskEntity::getUpdateTime, start.plusDays(1))
                .eq(TaskEntity::getTaskStatus, taskStatus);
        return this.count(qw);
    }





    /**
     * 生成工单编号
     *
     * @return
     */
    private String generateTaskCode() {
        //      日期字符串
        String date = LocalDate.now().format(DateTimeFormatter.ofPattern("yyyyMMdd"));
//        把当前序号存入redis中 ，key的值
        String key = "lkd:task:code:" + date;
        Long value = redisTemplate.opsForValue().increment(key);
        if (value == 1) {
//            只在第一次操作redis的时候，设置有效期
            redisTemplate.expire(key, 1, TimeUnit.DAYS);
        }
//        返回的工单号 日期+序号 ，序号如果不够4位，前面补0
        return date + Strings.padStart(value.toString(), 4, '0');
    }

    /**
     * 判断工单基础数据
     **/
    private void verifyTaskMsg(TaskViewModel taskViewModel) {

        if (StringUtils.isEmpty(taskViewModel.getInnerCode())) {
            throw new LogicException("售货机编号不能为空");
        }

        if (ObjectUtils.isEmpty(taskViewModel.getUserId())) {
            throw new LogicException("必须要指定员工");

        }
        if (ObjectUtils.isEmpty(taskViewModel.getProductType())) {
            throw new LogicException("工单类型不能为空");
        }

        if (StringUtils.isEmpty(taskViewModel.getDesc())) {
            throw new LogicException("工单描述不能为空");
        }

        if (VMSystem.TASK_TYPE_SUPPLY == taskViewModel.getProductType()) {
            if (CollectionUtils.isEmpty(taskViewModel.getDetails())) {
                throw new LogicException("补货工单补货详情不能为空");
            }
        }
    }

    /**
     * 创建工单校验
     *
     * @param vmStatus
     * @param productType
     * @throws LogicException
     */
    private void checkCreateTask(Integer vmStatus, int productType) throws LogicException {
        //如果是投放工单，状态为运营
        if (productType == VMSystem.TASK_TYPE_DEPLOY && vmStatus == VMSystem.VM_STATUS_RUNNING) {
            throw new LogicException("该设备已在运营");
        }

        //如果是维修工单，状态为运营
        if (productType == VMSystem.TASK_TYPE_REPAIR && vmStatus != VMSystem.VM_STATUS_RUNNING) {
            throw new LogicException("该设备已在运营");
        }


        //如果是补货工单，状态不是运营状态
        if (productType == VMSystem.TASK_TYPE_SUPPLY && vmStatus != VMSystem.VM_STATUS_RUNNING) {
            throw new LogicException("该设备不在运营状态");
        }

        //如果是撤机工单，状态不是运营状态
        if (productType == VMSystem.TASK_TYPE_REVOKE && vmStatus != VMSystem.VM_STATUS_RUNNING) {
            throw new LogicException("该设备不在运营状态");
        }
    }

    /**
     * 同一台设备下是否存在未完成的工单
     *
     * @param innerCode
     * @param productionType
     * @return
     */
    private boolean hasTask(String innerCode, int productionType) {
        QueryWrapper<TaskEntity> qw = new QueryWrapper<>();
        qw.lambda()
                .select(TaskEntity::getTaskId)
                .eq(TaskEntity::getInnerCode, innerCode)
                .eq(TaskEntity::getProductTypeId, productionType)
                .le(TaskEntity::getTaskStatus, VMSystem.TASK_STATUS_PROGRESS);
        return this.count(qw) > 0;
    }

    // 当日工单统计
    @Override
    public List<TaskReportInfoVO> taskReportInfo(LocalDateTime start, LocalDateTime end) {
        // 1.查询运营数据
        // 1-1 工单总数
        Integer supplyCount = this.taskCount(start,end,false,null);
        // 1-2 完成数量
        Integer supplyFinshCount = this.taskCount(start,end,false,VMSystem.TASK_STATUS_FINISH);
        // 1-3 拒绝数量
        Integer supplyCancelCount = this.taskCount(start, end, false, VMSystem.TASK_STATUS_CANCEL);
        // 1-4 进行中数量
        Integer supplyProgeressCount = this.taskCount(start, end, false, VMSystem.TASK_STATUS_PROGRESS);
        // 1-4 运营人员
        Integer operatorCount = userServiceFeignClient.getOperatorCount();
        // 1-5 封装数据
        TaskReportInfoVO supplyVo = new TaskReportInfoVO();
        supplyVo.setTotal(supplyCount);
        supplyVo.setCompletedTotal(supplyFinshCount);
        supplyVo.setCancelTotal(supplyCancelCount);
        supplyVo.setWorkerCount(operatorCount);
        supplyVo.setProgressTotal(supplyProgeressCount);
        supplyVo.setDate(LocalDate.now().toString());

        // 2.查询运维数据
        // 2-1 工单总数
        Integer repairCount = this.taskCount(start, end, true, null);
        // 2-2 完成数量
        Integer repairFinishCount = this.taskCount(start, end, true, VMSystem.TASK_STATUS_FINISH);
        // 2-3 拒绝数量
        Integer repairCancelCount = this.taskCount(start, end, true, VMSystem.TASK_STATUS_CANCEL);
        // 2-4 进行中数量
        Integer repairProgeressCount = this.taskCount(start, end, true, VMSystem.TASK_STATUS_PROGRESS);
        // 2-5 运维人员
        Integer workerCount = userServiceFeignClient.getRepairerCount();
        TaskReportInfoVO repairVo = new TaskReportInfoVO();
        repairVo.setTotal(repairCount);
        repairVo.setCompletedTotal(repairFinishCount);
        repairVo.setCancelTotal(repairCancelCount);
        repairVo.setProgressTotal(repairProgeressCount);
        repairVo.setWorkerCount(workerCount);
        repairVo.setRepair(true);
        repairVo.setDate(LocalDate.now().toString());
        // 3.封装数据并返回
        ArrayList<TaskReportInfoVO> voList = new ArrayList<>();
        voList.add(supplyVo);
        voList.add(repairVo);
        return voList;
    }

    @Autowired
    private VmServiceFeignClient vmServiceFeignClient;


    /*
    * 创建工单
    * */
    @Transactional
    @Override
    public void create(TaskViewModel taskViewModel) {
        //1. 校验基础数据(已提供:verifyTaskMsg方法)
        verifyTaskMsg(taskViewModel);
        //2. 通过feign查询并校验售货机是否存在
        VmVO vmVO = vmServiceFeignClient.findByInnerCode(taskViewModel.getInnerCode());
        if(ObjectUtil.isEmpty(vmVO)){
            throw new LogicException("售货机不存在");
        }
        //3. 验售货机的状态与工单类型是否相符 (已提供 :checkCreateTask方法)
        checkCreateTask(vmVO.getVmStatus(),taskViewModel.getProductType());
        // -如果是投放工单，状态必为未投放否则抛出异常
        // -如果是补货工单，状态必为运营状态则抛出异常
        // -如果是撤机工单，状态必为运营状态否则跑出异常

        //4.校验这台设备是否有未完成的同类型工单，如果有则不能创建(已提供:hasTask方法)
        if(hasTask(taskViewModel.getInnerCode(),taskViewModel.getProductType())){
            throw new LogicException("该设备有未完成的同类型工单，不能重复创建");
        }
        //5. 通过feign查询并校验执行工作人员是否存在
        UserVO userVO = userServiceFeignClient.findById(taskViewModel.getUserId());
        if(ObjectUtil.isEmpty(userVO)){
            throw new LogicException("此员工不存在，无法创建工单");
        }
        //6.校验非同区域下的工作人员不能接受工单
        if(!vmVO.getRegionId().equals(userVO.getRegionId())){
            throw new LogicException("此员工不负责此区域内工单，无法创建");
        }
        //7.保存工单信息(已提供:generateTaskCode方法)
        TaskEntity taskEntity = BeanUtil.copyProperties(taskViewModel, TaskEntity.class);
        taskEntity.setTaskCode(generateTaskCode());//工单编号 202307220001
        taskEntity.setTaskStatus(VMSystem.TASK_STATUS_CREATE);//工单状态
        taskEntity.setUserName(userVO.getUserName());//执行人名字
        taskEntity.setRegionId(userVO.getRegionId());//区域id
        taskEntity.setDescript(taskViewModel.getDesc());//工单描述
        taskEntity.setAddr(vmVO.getNodeAddr());//地址
        taskEntity.setProductTypeId(taskViewModel.getProductType());//工单类型
        this.save(taskEntity);

        //8.如果是补货工单，向工单明细表插入记录
        if(taskViewModel.getProductType() == VMSystem.TASK_TYPE_SUPPLY){
            List<TaskDetailsEntity> detailsList = taskViewModel.getDetails().stream().map(detailModel -> {
                TaskDetailsEntity taskDetailsEntity = BeanUtil.copyProperties(detailModel, TaskDetailsEntity.class);
                taskDetailsEntity.setTaskId(taskEntity.getTaskId());
                return taskDetailsEntity;
            }).collect(Collectors.toList());
            //保存数据库
            taskDetailsService.saveBatch(detailsList);
        }
        updateTaskZSet(taskEntity,1);
    }

    /*
    * 接受工单
    * */
    @Override
    public Boolean accept(Long taskId, Integer userId) {
      //1. 判断工单是否存在
        TaskEntity taskEntity = this.getById(taskId);
        if(ObjectUtil.isEmpty(taskEntity)){
            throw new LogicException("工单不存在");
        }
        //2. 判断工单状态是否为刚创建(待处理)
        if(taskEntity.getTaskStatus() != VMSystem.TASK_STATUS_CREATE){
            throw new LogicException("此工单状态不是待处理,无法接受");
        }
        //3.判断登陆人是否有权接受工单
        if(!userId.equals(taskEntity.getUserId())){
            throw new LogicException("此登陆人无权接受工单");
        }
        //4.修改工单状态
        taskEntity.setTaskStatus(VMSystem.TASK_STATUS_PROGRESS);
        return this.updateById(taskEntity);
    }

    /*
    * 拒绝/取消工单
    * */
    @Override
    public Boolean cancel(Long taskId, CancelTaskViewModel cancelTaskViewModel, Integer userId) {
       //1. 判断工单是否存在
        TaskEntity taskEntity = this.getById(taskId);
        if(ObjectUtil.isEmpty(taskEntity)){
            throw new LogicException("工单不存在!");
        }
        //2. 判断工单状态是否为刚创建(待处理)
        if(taskEntity.getTaskStatus() == VMSystem.TASK_STATUS_FINISH ||
        taskEntity.getTaskStatus() == VMSystem.TASK_STATUS_CANCEL){
            throw new LogicException("此工单状态不是待处理或进行中，无法取消");
        }
        //3.判断登陆人是否有权取消工单
        if(!userId.equals(taskEntity.getUserId())){
            throw new LogicException("此登陆人无权取消/拒绝工单");
        }
        //4.修改工单状态
        taskEntity.setTaskStatus(VMSystem.TASK_STATUS_CANCEL);
        taskEntity.setDescript(cancelTaskViewModel.getDesc());
        //5.返回结果
        updateTaskZSet(taskEntity,-1);
        return this.updateById(taskEntity);
    }

    /*
    * 完成工单
    * */
    @Override
    public Boolean complete(Long taskId, Integer userId) {
      //1. 判断工单是否存在
        TaskEntity taskEntity = this.getById(taskId);
        if(ObjectUtil.isEmpty(taskEntity)){
            throw new LogicException("工单不存在");
        }
        //2. 判断工单状态
        if(taskEntity.getTaskStatus()== VMSystem.TASK_STATUS_FINISH ||
        taskEntity.getTaskStatus() == VMSystem.TASK_STATUS_CANCEL ||
        taskEntity.getTaskStatus() == VMSystem.TASK_STATUS_CREATE){
            throw new LogicException("此工单状态不是进行中，无法完成");
        }
        //3. 判断登陆人是否有全校完成工单
        if(!userId.equals(taskEntity.getUserId())){
            throw new LogicException("此登陆人无权完成工单");
        }
        //4. 修改工单状态
        taskEntity.setTaskStatus(VMSystem.TASK_STATUS_FINISH);

        //5. 发送运维工单消息 (投放、撤机)
        if(taskEntity.getProductTypeId()==VMSystem.TASK_TYPE_DEPLOY
        || taskEntity.getProductTypeId()==VMSystem.TASK_TYPE_REVOKE){
            sendRepairMsg(taskEntity);
        }
        // 发送运营工单消息
        if(taskEntity.getProductTypeId() ==VMSystem.TASK_TYPE_SUPPLY){
            sendSupplyMsg(taskEntity);
        }

        //6.返回结果
        return this.updateById(taskEntity);
    }

    /*
    * 获取同一天内分配工单最少的人
    * */
    @Override
    public Integer getLeastUser(Long regionId, Boolean isRepair) {
        //1. 确定是运维角色还是运营角色
        String roleCode = VMSystem.USER_ROLE_SUPPLY_ODE; //默认运营角色
        if(isRepair == true){
            roleCode=VMSystem.USER_ROLE_REPAIRER_CODE;// 运维角色
        }
        //2. 获取redis中key
        String key = VMSystem.generateKey(regionId, roleCode);
        //3. 查询zset(升序)
        Set<String> userSet = redisTemplate.opsForZSet().range(key, 0, 0);
        if(CollUtil.isEmpty(userSet)){
            return null;
        }
        //jdk8新特性
        return Integer.parseInt(userSet.stream().findFirst().get());


    }

    /*
    * 获取设备自检信息，判断是否创建维修工单
    * */
    @Override
    public void autoRepairTask(VmStatusContract vmStatusContract) {
        //1. 查询售货机所在区域
        VmVO vmVO = vmServiceFeignClient.findByInnerCode(vmStatusContract.getInnerCode());
        //2. 获取该区域下维修人员工单最少的那个人
        Integer userId = getLeastUser(vmVO.getRegionId(), true);
        //3. 判断该设备是否需要维修
        Boolean isCreate = false;
        for (StatusInfo statusInfo : vmStatusContract.getStatusInfo()) {
            if(statusInfo.isStatus()==false){
                //需要维修
                isCreate=true;
                //跳出循环
                break;
            }
        }
        //4. 是否创建维修工单
        if(isCreate==true){
            //准备基础数据
            TaskViewModel taskViewModel = new TaskViewModel();
            taskViewModel.setCreateType(0);//自动工单
            taskViewModel.setInnerCode(vmStatusContract.getInnerCode());//设备编号
            taskViewModel.setUserId(userId);//干活人的人
            taskViewModel.setAssignorId(0);//指派人自动
            taskViewModel.setProductType(VMSystem.TASK_TYPE_REPAIR);//工单类型 维修
            taskViewModel.setDesc("自动创建维修工单");

            //调用创建工单方法
            create(taskViewModel);
        }
    }

    /*
    * 处理自动补货工单
    * */
    @Override
    public void autoSupplyTask(SupplyContract supplyContract) {
      // 查询设备
        VmVO vmVO = vmServiceFeignClient.findByInnerCode(supplyContract.getInnerCode());
        if(ObjectUtil.isEmpty(vmVO)){
            throw new LogicException("此设备不存在!");
        }
        //查询当天在此设备区域工单里最少的人
        Integer userId = getLeastUser(vmVO.getRegionId(), false);
        //创建工单对象
        TaskViewModel taskViewModel = new TaskViewModel();
        taskViewModel.setCreateType(0);//自动工单
        taskViewModel.setInnerCode(supplyContract.getInnerCode());//设备编号
        taskViewModel.setUserId(userId);//谁干活
        taskViewModel.setAssignorId(0);//自动创建
        taskViewModel.setProductType(VMSystem.TASK_TYPE_SUPPLY);//补货工单类型
        taskViewModel.setDesc("自动补货工单");

        // 添加补货工单详情表
        ArrayList<TaskDetailsViewModel> detaills = new ArrayList<>();
        for (SupplyChannel sc : supplyContract.getSupplyData()) {
            // 创建
            TaskDetailsViewModel taskDetailsViewModel = new TaskDetailsViewModel();
            taskDetailsViewModel.setChannelCode(sc.getChannelCode());//货道号
            taskDetailsViewModel.setExpectCapacity(sc.getCapacity());//补几件
            taskDetailsViewModel.setSkuId(sc.getSkuId());//商品id
            taskDetailsViewModel.setSkuName(sc.getSkuName());//商品名称
            taskDetailsViewModel.setSkuImage(sc.getSkuImage());//商品名称
            detaills.add(taskDetailsViewModel);
        }
        taskViewModel.setDetails(detaills);
        //调用创建工单方法
        create(taskViewModel);
    }

    @Override
    public void autoSupplyTask(int total, int index) {
//        //1. 查询所有运营中的设备列表
//        List<VendingMachineEntity> vmList = this.lambdaQuery()
//                .eq(VendingMachineEntity::getVmStatus,VMSystem.VM_STATUS_RUNNING)
//                .apply("mod(id," + total + ")=" + index)
//                .list();
//        log.info(vmList.toString());

    }

    // 抽取发送运营工单消息方法
    private void sendSupplyMsg(TaskEntity taskEntity) {
      //1. 组装消息内容
        SupplyContract supplyContract = new SupplyContract();
        // 1-1 售货机编号
        supplyContract.setInnerCode(taskEntity.getInnerCode());
        //1-2 工单详情
        LambdaQueryWrapper<TaskDetailsEntity> qw = new LambdaQueryWrapper<>();
        qw.eq(TaskDetailsEntity::getTaskId,taskEntity.getTaskId());
        List<TaskDetailsEntity> detailsEntityList = taskDetailsService.list(qw);
        List<SupplyChannel> supplyChannelList = detailsEntityList.stream().map(taskDetailsEntity -> {
            //封装补货数据
            SupplyChannel supplyChannel = new SupplyChannel();
            supplyChannel.setChannelCode(taskDetailsEntity.getChannelCode());//货道号
            supplyChannel.setCapacity(taskDetailsEntity.getExpectCapacity());//补货数量
            return supplyChannel;
        }).collect(Collectors.toList());
        supplyContract.setSupplyData(supplyChannelList);
        //2. 发送消息
        try {
            producer.send(TopicConfig.VMS_SUPPLY_TOPIC,2,supplyContract);
        }catch (Exception e){
            e.printStackTrace();
            throw new LogicException("发送运营工单消息失败"+taskEntity.getTaskId());
        }

    }

    @Autowired
    private MqttProducer producer;

    // 抽取发送运维工单消息方法
    private void sendRepairMsg(TaskEntity taskEntity) {
     //1. 准备消息发送
        TaskCompleteContract taskCompleteContract = new TaskCompleteContract();
        taskCompleteContract.setInnerCode(taskEntity.getInnerCode());
        taskCompleteContract.setTaskType(taskEntity.getProductTypeId());
        //2.发送消息
        try {
            producer.send(TopicConfig.VMS_SUPPLY_TOPIC,2,taskCompleteContract);
        }catch (Exception e){
            throw new LogicException("运维工单消息发送失败: "+taskEntity.getTaskId());
        }

    }

    // 统计工单数量
    private Integer taskCount(LocalDateTime start, LocalDateTime end, Boolean isRepair, Integer taskStatus) {
        LambdaQueryWrapper<TaskEntity> qw = new LambdaQueryWrapper<>();
        qw.between(TaskEntity::getCreateTime, start, end);
        // 判断是否为运维工单
        if (isRepair) {
            // 运维工单
            qw.ne(TaskEntity::getProductTypeId, VMSystem.TASK_TYPE_SUPPLY);
        } else {
            // 运营工单
            qw.eq(TaskEntity::getProductTypeId, VMSystem.TASK_TYPE_SUPPLY);
        }
        // 判断是否提供工单状态
        qw.eq(ObjectUtil.isNotEmpty(taskStatus), TaskEntity::getTaskStatus, taskStatus);

        return this.count(qw);
    }


    /*
    * 更新工单量列表
    * */
    private void updateTaskZSet(TaskEntity task,int score){
       //1. 确定角色code(根据工单类型确认)
        String roleCode=VMSystem.USER_ROLE_REPAIRER_CODE;// 初始值 运维角色
        if(task.getProductTypeId().equals(VMSystem.TASK_TYPE_SUPPLY)){
            //运营角色
            roleCode=VMSystem.USER_ROLE_SUPPLY_ODE;
        }
        //2. 获取key
        String key = VMSystem.generateKey(task.getRegionId(), roleCode);
        //3. zset数量+1 或 -1
        redisTemplate.opsForZSet().incrementScore(key,task.getUserId().toString(),score);

    }

}
